package com.zouk.sdk.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.taosdata.jdbc.tmq.TaosConsumer;
import com.zouk.sdk.models.Config;

import java.util.Map;
import java.util.Properties;

/**
 * @author ：liujl
 * @date ：Created 2023/12/26 14:32
 * @description：消费订阅服务
 */
public class ConsumerSubscribeService {

    public TaosConsumer<Map<String, Object>> getConsumer(String url, String accessKeyId, String accessKeySecret, String securityToken) {
        return this.init(this.getConfig(url, accessKeyId, accessKeySecret, securityToken));
    }

    private TaosConsumer<Map<String, Object>> init(Properties properties) {
        try {
             return new TaosConsumer<>(properties);
        } catch (Exception e) {
            throw new RuntimeException("init consumer sdk fail! message:" + e.getMessage(), e);
        }
    }

    private Properties getConfig(String url, String accessKeyId, String accessKeySecret, String securityToken) {
        Config config = new Config().builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret).build();
        String body = HttpRequest.post(url)
                .header(Header.AUTHORIZATION, securityToken)
                .body(JSONUtil.toJsonStr(config))
                .execute().body();
        if (StrUtil.isNotBlank(body)) {
            JSONObject resultBody = JSONUtil.parseObj(body);
            Integer code = resultBody.getInt("code");
            if (code == 200) {
                String data = resultBody.getStr("data");
                if (StrUtil.isNotBlank(data)) {
                    return resultBody.getBean("data", Properties.class);
                }
            }
        }
        return null;
    }
}
